<template>
  <div class="pageTableView" style="height: 100%; overflow: auto;">
    <div class="pageTableButView"><el-button type="primary" @click="showDialog('add')">通用排班</el-button></div>
    <div class="pageContent">
      <div class="pageContentLeft">
        <p class="pageContentTitle">产线管理</p>
        <el-tree node-key="id" default-expand-all :data="workRoomList" :props="defaultProps"
          @node-click="handleNodeClick" :expand-on-click-node="false" :highlight-current="true" ref="tree">
          <template #default="{ node, data }">
            <div class="custom-tree-node"> <span :class="data.id == currentNodeKey ? 'is-penultimate' : ''">{{
                data.orgName }}</span></div>
          </template>
        </el-tree>
      </div>
      <div class="pageContentRight">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
          <el-tab-pane label="周视图" name="weeks">
            <WeekFactory ref="childRef" :editApi="editApi" :currentNodeKey="currentNodeKey" :weekDays="weekDays" />
          </el-tab-pane>
          <el-tab-pane label="月视图" name="moments">
            <el-calendar v-model="value" class="custom-calendar">
              <template #date-cell="{ data }">
                <div class="date-cell" @dblclick="showDialog(parsedFind(data.day))">
                  <span class="date-cell-title"> {{ formatDate(data.day) }}</span>
                  <div v-if="parsedFind(data.day)" class="calendarBox">
                    <div v-for="(item, index) in parsedFind(data.day).chlendarJson" :key="index">
                      <div class="calendarItem" :style="{ background: item.isProduction ? '#d9edfe' : 'rgba(0,0,0,0.12)' }">
                        <span>{{ item.shiftNameValue }}</span>
                        <span> {{ item.startTime }} - {{ item.endTime }} </span>
                        <span> {{ item.teamName }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </el-calendar></el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- 弹框 -->
    <el-dialog title="排班详情" v-model="dialogVisible" width='900' @close="handleDialogClose"
      :modal-class="'custom-dialog-modal'">
      <el-form :model="form" ref="formRef" :rules="rules">
        <el-form-item label="选择日期" prop="times" label-width="80px">
          <el-date-picker v-model="form.times" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss" :disabled="form.edit" />
        </el-form-item>
        <el-form-item label="上班时间" prop="weekList" label-width="80px">
          <el-select v-model="form.weekList" placeholder="请选择" multiple :disabled="form.edit">
            <el-option v-for="item in weekDays" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择班次" prop="shiftId" label-width="80px">
          <el-select v-model="form.shiftId" placeholder="请选择" @change="handleOptionChange">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <template v-if="form.chlendarJson && form.chlendarJson.length">
          <el-form-item v-for="(item, index) in form.chlendarJson" :key="item.shiftName"
            :label="changeName(item.shiftName)">
            <el-row :gutter="20">
              <el-col :span="5">
                <el-form-item :prop="`chlendarJson.${index}.startTime`" :rules="rules.startTime">
                  <el-time-picker v-model="item.startTime" placeholder="开始时间" format="HH:mm"
                    value-format="HH:mm"></el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="1" style="text-align: center;">-</el-col>
              <el-col :span="5">
                <el-form-item :prop="`chlendarJson.${index}.endTime`" :rules="rules.endTime">
                  <el-time-picker v-model="item.endTime" placeholder="结束时间" format="HH:mm"
                    value-format="HH:mm"></el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item :prop="`chlendarJson.${index}.teamId`" :rules="rules.group" label="班组">
                  <el-select v-model="item.teamId" placeholder="选择班组">
                    <el-option v-for="group in optionsTeam" :key="group.id" :label="group.name"
                      :value="group.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="7"> <el-form-item label-width="90px" :prop="`chlendarJson.${index}.restTime`"
                  :rules="rules.restTime" label="休息时长">
                  <el-input-number v-model="item.restTime" placeholder="休息时间（分钟）" :min="0"></el-input-number>
                </el-form-item></el-col>
            </el-row>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSchedule">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axisInstance from '@/utils/http/api';
import dayjs from 'dayjs';
import WeekFactory from './weekFactory.vue';

export default {

  components: {
    WeekFactory
  },
  setup() {
    const value = ref(new Date());
    const dialogVisible = ref(false);
    const selectedDate = ref(null);
    const activeName = ref('weeks');
    const childRef = ref(null);

    const tree = ref(null)
    const form = ref({
      times: [],

      shiftId: '',
      chlendarJson: []
    });
    const options = ref([]);
    const optionsTeam = ref([]);
    const optionsMoment = ref();
    const classOptions = ref([
      {
        label: '早班',
        value: '0'
      }, {
        label: '中班',
        value: '1'
      }, {
        label: '晚班',
        value: '2'
      }
    ]);
    //不要随意改变顺序·
    const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    const rules = {
      times: [{ required: true, message: '请选择日期范围', trigger: 'change' }],
      appointTime: [{ required: true, message: '请选择上班时间', trigger: 'change' }],
      shiftId: [{ required: true, message: '请选择班次', trigger: 'change' }],
      startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
      endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
      group: [{ required: true, message: '请选择班组', trigger: 'change' }],
      restTime: [{ required: true, message: '请输入休息时间', trigger: 'change' }]
    };
    const defaultProps = {
      children: 'sonList',
      label: 'orgName',
      disabled: 'disabled',
    }
    const workRoomList = ref([]); // 车间
    const currentNodeKey = ref('');
    const editApi = (row) => {
      showDialog(row)
    }
    const handleClick = (tab, event) => {
      if (childRef.value && childRef.value.childMethod && tab.paneName === 'weeks') {
        childRef.value.childMethod();
      } else {
        momentList()
      }
    };
    const parsedFind = (day) => {
      const lastMonth = dayjs(day).format('YYYY-MM-DD');
      const showDay = optionsMoment.value?.find(i => dayjs(i.appointTime
      ).format('YYYY-MM-DD') === lastMonth) || {}
      return showDay
    }
    const momentList = () => {
      const startDate = dayjs(value.value).startOf('month').format('YYYY-MM-DD HH:mm:ss');
      const endDate = dayjs(value.value).add(1, 'month').startOf('month').format('YYYY-MM-DD HH:mm:ss');
      const calendar = {
        startDate,
        endDate,
        organizationId: currentNodeKey.value
      };
      axisInstance.post('/api/factoryCalendar/getAll', { ...calendar })
        .then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return false;
          }
          optionsMoment.value = res.data.map(item => {
            return {
              ...item,
              chlendarJson: JSON.parse(item.chlendarJson)
            }
          });
        });

    }
    const getOption = () => {
      axisInstance.post('/api/basedataOrganization/getAll', {})
        .then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return false;
          }
          const organizationData = res.data.map(item => {
            const tier = item.sonList.map(i => {
              return { ...i, levels: 2 ,sonList:undefined}
            })
            return { ...item, sonList: tier }
          })

          workRoomList.value = organizationData
          if (organizationData?.[0].sonList) {

            currentNodeKey.value = organizationData[0].sonList?.[0].id
            // tree.value.setCurrentKey(organizationData[0].sonList[0].id)
            childRef.value.childMethod(organizationData[0].sonList[0].id);
          } else {
            currentNodeKey.value = null
          }

        });
      axisInstance.post('/api/swingShift/getAll', {})
        .then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return false;
          }
          options.value = res.data;
        });

      axisInstance.post('/api/basedataTeam/getAll', {})
        .then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return false;
          }
          optionsTeam.value = res.data;
        });
    };

    const handleOptionChange = (value) => {
      const shiftId = options.value.find(option => option.id === value);
      if (shiftId) {
        const shiftJson = JSON.parse(shiftId.shiftJson);
        form.value.chlendarJson = shiftJson.map((shift, index) => ({
          ...shift,
          startTime: shift.startTime,
          endTime: shift.endTime,
          restTime: shift.restTime,
          group: undefined, // 初始化班组为空
          index: index // 添加索引
        }));
      } else {
        form.value.chlendarJson = [];
      }
    };
    const changeName = (nameId) => {
      return classOptions.value.find(item => item.value === nameId).label
    }
    const showDialog = (day) => {

      if (day === 'add') {
        form.value = {};
      } else if (day.appointTime) {
        form.value = {
          times: [
            dayjs(day.appointTime).format('YYYY-MM-DD HH:mm:ss'),
            dayjs(day.appointTime).add(1, 'day').format('YYYY-MM-DD HH:mm:ss')

          ],
          shiftId: day.shiftId,
          weekList: [day.week],
          chlendarJson: day.chlendarJson,
          edit: true,
          typeDay: day.typeDay
        };
      } else {
        const dayWeek = dayjs(value.value).day();
        form.value = {
          times: [
            dayjs(value.value).format('YYYY-MM-DD HH:mm:ss'),
            dayjs(value.value).add(1, 'day').format('YYYY-MM-DD HH:mm:ss')

          ],
          weekList: [weekDays[dayWeek]],
          chlendarJson: [],
          edit: true
        };
      }

      selectedDate.value = day;
      dialogVisible.value = true;
    };

    const handleDialogClose = () => {
      selectedDate.value = null;
    };
    const saveSchedule = () => {
      const chlendarJson = form.value.chlendarJson.map(item => {
        return {
          ...item,
          teamCode: optionsTeam.value.find(i => i.id === item.teamId).code,
          teamName: optionsTeam.value.find(i => i.id === item.teamId).name,
          shiftNameValue: classOptions.value.find(i => i.value === item.shiftName).label,
          isProduction: true
        }
      })
      const paramsData = {
        ...form.value,
        weekList: form.value.weekList,
        startDate: form.value.times[0],
        endDate: form.value.times[1],
        times: undefined,
        organizationId: currentNodeKey.value,
        chlendarJson: JSON.stringify(chlendarJson),

      }
      axisInstance.post('/api/factoryCalendar/create', { ...paramsData })
        .then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('排班成功');
          if (activeName.value === 'weeks') {
            childRef.value.childMethod();
          } else {
            momentList()
          }

          dialogVisible.value = false;
        });
};

    const formatDate = (date) => {
      return dayjs(date).format('MM-DD');
    };

    watch(value, (newValue, oldValue) => {
      const newMonth = dayjs(newValue).month();
      const oldMonth = dayjs(oldValue).month();
      if (newMonth !== oldMonth) {
        momentList();

      }
    });
    const handleNodeClick = (data, node) => {
      if (data.levels !== 2) {
        ElMessage.warning('只能选择第二层级节点');
        return;
      }
      currentNodeKey.value = data.id;
      if (activeName.value === 'weeks') {
        childRef.value.childMethod(data.id);
      } else {
        momentList()
      }

      console.log(currentNodeKey.value, ' currentNodeKey.value ')
    }

    onMounted(() => {
      getOption();
      // handleClick({ paneName: 'weeks' })
    });


    return {
      value,
      dialogVisible,
      selectedDate,
      form,
      options,
      optionsTeam,
      rules,
      weekDays,
      activeName,
      childRef,
      handleClick,
      showDialog,
      handleDialogClose,
      saveSchedule,
      formatDate,
      changeName,
      parsedFind,
      editApi,
      handleOptionChange,
      handleNodeClick,
      defaultProps,
      workRoomList,
      currentNodeKey
    };
  },
};
</script>

<style scoped lang="scss">
.pageTableView {
  position: relative;
}

.pageTableButView {
  position: absolute;
  right: 2%;
  z-index: 2;
}

.date-cell {
  width: 100%;
  height: 90px;
  overflow: auto;
}

.custom-calendar {
  height: 100%;
}

::v-deep .el-calendar .custom-calendar {
  background: #fff;
}

::v-deep .el-calendar-table .el-calendar-day {
  height: 100px;
}

.date-cell-title {
  float: right;
  width: 100%;
  padding: 2px;
}

.calendarItem {
  display: flex;
  width: 100%;
  background: #d9edfe;
  border-radius: 2px;
  padding: 5px;
  justify-content: space-between;
  margin-bottom: 4px;
  font-size: 11px;

  span:nth-child(1) {
    color: #035beb;
  }

  span:nth-child(2) {
    color: #828282;
  }

  span:nth-child(3) {
    color: #035beb;
  }
}

.date-cell::-webkit-scrollbar {
  width: 2px;
  /* 滚动条宽度 */
}

.date-cell::-webkit-scrollbar-track {
  background: transparent;
  /* 滚动条轨道背景色 */
}

.date-cell::-webkit-scrollbar-thumb {
  background: #ffffff27;
  /* 滚动条拇指背景色 */
  border-radius: 1px;
  /* 滚动条拇指圆角 */
}

.date-cell::-webkit-scrollbar-thumb:hover {
  background: #ffffff27;
  /* 滚动条拇指悬停背景色 */
}

.pageContent {
  width: 100%;
  height: 100%;
  display: flex;
}

.pageContentLeft {
  width: 15%;
  overflow: auto;
}

.pageContentLeft::-webkit-scrollbar {
  width: 3px;
  /* 滚动条宽度 */
}

.pageContentRight {
  width: 85%;

}

.is-penultimate {
  color: #626aef;
  font-weight: 700;
}
.pageContentTitle{
  font-weight: bold;
  padding: 10px;
}
</style>